﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using nj4x;
using nj4x.Metatrader;
using System.Windows.Forms;

namespace Traders.Models
{
    public class Account
    {
        private static String server = "127.0.0.1";
        private static int port = 7788;

        private String _login = "";
        public String Login
        {
            get { return _login; }
            set { _login = value; }
        }

        private String _password = "";
        public String Password
        {
            get { return _password; }
            set { _password = value; }
        }

        private String _broker = "";
        public String Broker
        {
            get { return _broker; }
            set { _broker = value; }
        }

        private Strategy strategy = new Strategy();
        public Strategy Strategy { get { return strategy; } }        
        
        public Account()
        {
        }

        public Account(String Login, String Password, String Broker)
            : this()
        {
            this._login = Login;
            this._password = Password;
            this._broker = Broker;
        }

        public Account(String Login, String Password, String Broker, Strategy strategy)
            : this(Login, Password, Broker)
        {
            this.strategy = strategy;
        }

        public bool Connect() 
        {
            try
            {
                strategy.Connect(server, port, new Broker(Broker), Login, Password);
            }
            catch (Exception e)
            {
                return false;
            }
            return true;
        }
        
        public List<IOrderInfo> getOpenTrades()
        {
            List<IOrderInfo> orders = new List<IOrderInfo>();

            for (int i = 0; i < strategy.OrdersTotal(); i++)
                orders.Add(strategy.OrderGet(i, SelectionType.SELECT_BY_POS, SelectionPool.MODE_TRADES));
            return orders;

        }

        public bool CloseTrade(int Ticket)
        {
            try
            {
                if (strategy.OrderSelect(Ticket, SelectionType.SELECT_BY_TICKET, SelectionPool.MODE_TRADES))
                    return strategy.OrderClose(Ticket, strategy.OrderLots(), strategy.OrderClosePrice(), 0, Color.HotPink);
            }
            catch (Exception e) { Console.WriteLine(e.Message + ", Error: " + strategy.GetLastError()); }
            
            return false;
        }
    }
}
